#!/bin/bash

BASEDIR=`pwd`
mkdir -p ./output/libs/

CMAKE_FLAG=""

case "$1" in
    release)
        CMAKE_FLAG="$CMAKE_FLAG -DBUILD_TYPE:STRING=release"
        ;;
    debug)
        CMAKE_FLAG="$CMAKE_FLAG -DBUILD_TYPE:STRING=debug"
        ;;
    *)
        ;;
esac


# build openssl
# https://www.openssl.org/source/openssl-1.1.1w.tar.gz

if [ ! -f $BASEDIR/libs/openssl/lib/libcrypto.a ] || [ ! -f $BASEDIR/libs/openssl/lib/libssl.a ]; then
    cd libs
    tar -zxvf openssl-1.1.1w.tar.gz
    cd openssl-1.1.1w
    # export LD_LIBRARY_PATH=$BASEDIR/libs/openssl/lib/:$LD_LIBRARY_PATH
    export LDFLAGS="-Wl,-rpath=$BASEDIR/libs/openssl/lib/"
    ./config --prefix=$BASEDIR/libs/openssl/
    make -j 32 && make install
    cd $BASEDIR
fi


# build yaml
# https://pyyaml.org/download/libyaml/yaml-0.2.5.zip

if [ ! -f $BASEDIR/libs/yaml/lib/libyaml.a ]; then
    cd libs
    rm -rf yaml-0.2.5
    unzip yaml-0.2.5.zip
    cd yaml-0.2.5
    ./configure --prefix=$BASEDIR/libs/yaml/
    make -j 32 && make install
    cd $BASEDIR
fi


# copy exp config file to tmp dir
cp -r test/conf/core_exp.yaml           /tmp/
cp -r test/conf/listeners_exp.yaml      /tmp/
cp -r test/conf/http_main.yaml          /tmp/http/main.yaml
rm -rf /tmp/http/sites_enabled/*
mkdir -p /tmp/http/sites_enabled/
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/www.a.com.yaml
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/www.b.com.yaml
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/www.c.com.yaml
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/www.d.com.yaml
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/www.e.com.yaml
cp -r test/conf/site_exp.yaml           /tmp/http/sites_enabled/\*.a.com.yaml


if [ ! -d "$BASEDIR/obj" ]; then
    echo "not found obj dir, please exec ./configure first"
    exit 1
fi

cd ./output/                        \
    && cmake ../  $CMAKE_FLAG       \
    && make -j 8
